<template>
  <div class="page-container">
    <div class="page-header">
      <div class="page-header-actions">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/workflow-templates' }">工作流模板管理</el-breadcrumb-item>
          <el-breadcrumb-item>模板详情</el-breadcrumb-item>
        </el-breadcrumb>
        <div class="action-buttons">
          <el-button @click="handleBack">
            <el-icon><Back /></el-icon>
            返回
          </el-button>
          <el-button type="primary" @click="handleEdit">
            <el-icon><Edit /></el-icon>
            编辑
          </el-button>
          <el-button type="success" @click="handleVersionHistory">
            <el-icon><Clock /></el-icon>
            版本历史
          </el-button>
        </div>
      </div>
    </div>

    <el-card v-loading="loading" class="detail-card">
      <!-- 基本信息 -->
      <template #header>
        <div class="card-header">
          <span class="card-title">基本信息</span>
          <el-tag type="primary">v{{ template.version }}</el-tag>
        </div>
      </template>

      <el-descriptions :column="2" border>
        <el-descriptions-item label="ID">{{ template.id }}</el-descriptions-item>
        <el-descriptions-item label="模板名称">{{ template.name }}</el-descriptions-item>
        <el-descriptions-item label="描述" :span="2">
          {{ template.description || '无' }}
        </el-descriptions-item>
        <el-descriptions-item label="当前版本">
          v{{ template.version }}
        </el-descriptions-item>
        <el-descriptions-item label="父版本ID">
          {{ template.parent_version_id || '无（初始版本）' }}
        </el-descriptions-item>
        <el-descriptions-item label="版本变更说明" :span="2">
          {{ template.change_log || '无' }}
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ formatDate(template.created_at) }}
        </el-descriptions-item>
        <el-descriptions-item label="更新时间">
          {{ formatDate(template.updated_at) }}
        </el-descriptions-item>
        <el-descriptions-item label="创建人" :span="2">
          {{ template.created_by || '系统' }}
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 工作流可视化 -->
    <el-card class="detail-card">
      <template #header>
        <span class="card-title">工作流定义</span>
      </template>

      <div class="workflow-visualization">
        <WorkflowEditor
          v-model="workflowData"
          :readonly="true"
        />
      </div>
    </el-card>

    <!-- 模板使用实例列表 -->
    <el-card class="detail-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">基于此模板的实例</span>
          <div>
            <!-- <el-button size="small" @click="handleCreateInstance">
              <el-icon><Plus /></el-icon>
              创建实例
            </el-button> -->
            <el-button size="small" @click="refreshInstances">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        :data="instances"
        v-loading="instancesLoading"
        stripe
      >
        <el-table-column prop="id" label="实例ID" width="100" />
        <el-table-column prop="instance_name" label="实例名称" min-width="200" />
        <el-table-column prop="template_version" label="模板版本" width="100">
          <template #default="{ row }">
            <el-tag size="small">v{{ row.template_version }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getInstanceStatusType(row.status)">{{ row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="trigger_type" label="触发方式" width="100">
          <template #default="{ row }">
            <el-tag v-if="row.trigger_type === 'manual'" type="primary" size="small">手动</el-tag>
            <el-tag v-else type="info" size="small">定时</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleViewInstance(row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="instancePagination.page"
        v-model:page-size="instancePagination.pageSize"
        :page-sizes="[10, 20, 50]"
        :total="instancesTotal"
        layout="total, sizes, prev, pager, next"
        class="pagination"
        @size-change="fetchInstances"
        @current-change="fetchInstances"
      />
    </el-card>

    <!-- 创建实例对话框 -->
    <el-dialog
      v-model="createInstanceDialogVisible"
      title="从模板创建实例"
      width="600px"
    >
      <el-form :model="instanceForm" label-width="120px">
        <el-form-item label="实例名称" required>
          <el-input v-model="instanceForm.instance_name" placeholder="请输入实例名称" />
        </el-form-item>
        <el-form-item label="触发人">
          <el-input v-model="instanceForm.trigger_user" placeholder="请输入触发人" />
        </el-form-item>
        <!-- <el-form-item label="输入参数">
          <el-input
            v-model="instanceForm.input_params"
            type="textarea"
            :rows="4"
            placeholder='输入JSON格式的参数，例如: {"key": "value"}'
          />
        </el-form-item> -->
        <el-form-item label="定时调度">
          <el-switch v-model="instanceForm.cron_enabled" />
        </el-form-item>
        <el-form-item v-if="instanceForm.cron_enabled" label="Cron表达式">
          <el-input
            v-model="instanceForm.cron_expression"
            placeholder="例如: 0 2 * * * (每天凌晨2点)"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createInstanceDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmCreateInstance">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useWorkflowTemplateStore } from '@/stores/workflowTemplate'
import { getWorkflowInstances } from '@/api/workflow'
import WorkflowEditor from '@/components/WorkflowEditor/index.vue'
import dayjs from 'dayjs'

const router = useRouter()
const route = useRoute()
const templateStore = useWorkflowTemplateStore()

const templateId = ref(parseInt(route.params.id))
const loading = ref(false)
const template = ref({})

const createInstanceDialogVisible = ref(false)
const instanceForm = reactive({
  instance_name: '',
  trigger_user: '',
  input_params: '',
  cron_enabled: false,
  cron_expression: ''
})

// 计算工作流数据格式，转换为Vue Flow格式
const workflowData = computed(() => {
  if (!template.value.workflow_definition || !template.value.workflow_definition.nodes) {
    return { nodes: [], edges: [] }
  }

  const definition = template.value.workflow_definition
  const edges = []
  const nodePositions = new Map()

  // 第一步：构建边的映射和入度统计
  const nodeMap = new Map()
  const inDegree = new Map()

  definition.nodes.forEach(node => {
    nodeMap.set(node.id, node)
    inDegree.set(node.id, 0)
  })

  // 统计入度并创建边
  definition.nodes.forEach(node => {
    if (node.next) {
      const nextNodes = Array.isArray(node.next) ? node.next : [node.next]
      nextNodes.forEach(nextId => {
        if (inDegree.has(nextId)) {
          inDegree.set(nextId, inDegree.get(nextId) + 1)
        }

        edges.push({
          id: `edge_${node.id}_${nextId}`,
          type: 'smoothstep',
          source: node.id,
          target: nextId,
          sourceHandle: 'source',
          targetHandle: 'target',
          animated: true,
          label: '',
          data: {}
        })
      })
    }
  })

  // 第二步：拓扑排序，按执行顺序排列节点
  const sortedNodes = []
  const queue = []

  // 找到所有入度为0的节点（起始节点）
  inDegree.forEach((degree, nodeId) => {
    if (degree === 0) {
      queue.push(nodeId)
    }
  })

  // BFS拓扑排序
  while (queue.length > 0) {
    const nodeId = queue.shift()
    sortedNodes.push(nodeId)

    const node = nodeMap.get(nodeId)
    if (node && node.next) {
      const nextNodes = Array.isArray(node.next) ? node.next : [node.next]
      nextNodes.forEach(nextId => {
        if (inDegree.has(nextId)) {
          inDegree.set(nextId, inDegree.get(nextId) - 1)
          if (inDegree.get(nextId) === 0) {
            queue.push(nextId)
          }
        }
      })
    }
  }

  // 如果有环或孤立节点，将剩余节点添加到末尾
  definition.nodes.forEach(node => {
    if (!sortedNodes.includes(node.id)) {
      sortedNodes.push(node.id)
    }
  })

  // 第三步：根据拓扑排序结果设置水平位置
  sortedNodes.forEach((nodeId, index) => {
    const x = 180 + index * 300
    const y = 90
    nodePositions.set(nodeId, { x, y })
  })

  // 转换节点格式
  const nodes = definition.nodes.map(node => {
    const position = nodePositions.get(node.id) || { x: 0, y: 0 }

    // 统一节点类型名称
    let nodeType = node.type
    if (node.type === 'condition') {
      nodeType = 'condition_branch'
    }

    return {
      id: node.id,
      type: nodeType,
      position,
      data: {
        label: node.name || node.type,
        config: node.config || {}
      }
    }
  })

  return { nodes, edges }
})

const instances = ref([])
const instancesLoading = ref(false)
const instancesTotal = ref(0)
const instancePagination = reactive({
  page: 1,
  pageSize: 10
})

const formatDate = (date) => {
  return date ? dayjs(date).format('YYYY-MM-DD HH:mm:ss') : ''
}

const getInstanceStatusType = (status) => {
  const typeMap = {
    '运行中': 'primary',
    '已完成': 'success',
    '失败': 'danger',
    '暂停中': 'warning',
    '已暂停': 'info',
    '等待中': 'warning',
    '已取消': 'info',
    '初始化': 'info'
  }
  return typeMap[status] || 'info'
}

const fetchTemplate = async () => {
  loading.value = true
  try {
    const data = await templateStore.fetchTemplateDetail(templateId.value)
    template.value = data
  } catch (error) {
    console.error('获取模板详情失败:', error)
    ElMessage.error('获取模板详情失败')
  } finally {
    loading.value = false
  }
}

const fetchInstances = async () => {
  instancesLoading.value = true
  try {
    const data = await getWorkflowInstances({
      template_id: templateId.value,
      page: instancePagination.page,
      page_size: instancePagination.pageSize
    })
    instances.value = data.items || []
    instancesTotal.value = data.total || 0
  } catch (error) {
    console.error('获取实例列表失败:', error)
    ElMessage.error('获取实例列表失败')
  } finally {
    instancesLoading.value = false
  }
}

const refreshInstances = () => {
  instancePagination.page = 1
  fetchInstances()
}

const handleBack = () => {
  router.push('/workflow-templates')
}

const handleEdit = () => {
  router.push(`/workflow-templates/${templateId.value}/edit`)
}

const handleVersionHistory = () => {
  router.push(`/workflow-templates/${templateId.value}/versions`)
}

const handleCreateInstance = () => {
  // 预填充实例名称
  instanceForm.instance_name = `${template.value.name}_${dayjs().format('YYYYMMDDHHmmss')}`
  instanceForm.input_params = ''
  instanceForm.cron_enabled = false
  instanceForm.cron_expression = ''
  createInstanceDialogVisible.value = true
}

const handleConfirmCreateInstance = async () => {
  if (!instanceForm.instance_name) {
    ElMessage.warning('请输入实例名称')
    return
  }

  try {
    let inputParams = {}
    if (instanceForm.input_params) {
      try {
        inputParams = JSON.parse(instanceForm.input_params)
      } catch (e) {
        ElMessage.error('输入参数格式错误，请输入有效的JSON')
        return
      }
    }

    await templateStore.createInstanceFromTemplate({
      template_id: templateId.value,
      instance_name: instanceForm.instance_name,
      trigger_user: instanceForm.trigger_user || null,
      input_params: inputParams,
      cron_enabled: instanceForm.cron_enabled,
      cron_expression: instanceForm.cron_expression || null
    })

    ElMessage.success('实例创建成功')
    createInstanceDialogVisible.value = false
    refreshInstances()
  } catch (error) {
    console.error('创建实例失败:', error)
    ElMessage.error(error.response?.data?.detail || '创建实例失败')
  }
}

const handleViewInstance = (row) => {
  router.push(`/workflows/instances/${row.id}`)
}

onMounted(() => {
  fetchTemplate()
  fetchInstances()
})
</script>

<style lang="scss" scoped>
.detail-card {
  margin-bottom: 20px;

  :deep(.el-card__header) {
    padding: 16px 20px;
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.page-header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.workflow-visualization {
  height: 500px;

  :deep(.workflow-editor-container) {
    height: 100%;
  }
}
</style>
